package com.xxx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginAccessFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //基于HTTP请求
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;

        //获取请求的路径
        String url = request.getRequestURI();
        System.out.println(url);

        //1、指定页面，放行（无需登录即可访问的页面，如登录，注册页面）
        if (url.contains("/Login.jsp")||url.contains("/Register.jsp")){
            //放行语句
            filterChain.doFilter(request,response);
            return;
        }

        //2、静态页面，放行（img，css，js文件等）
        if (url.contains("/js")||url.contains("/img")||url.contains("/css")){
            //放行语句
            filterChain.doFilter(request,response);
            return;
        }

        //3、指定操作，放行（无需登录即可执行的操作，例如：登录操作，注册操作）
        if (url.contains("Test")||url.contains("registerSubmit.jsp")){
            //放行语句
            filterChain.doFilter(request,response);
            return;
        }

        //4、登录状态，放行（判断session中用户信息是否为空）
        String uname = (String) request.getSession().getAttribute("userName");
        if (uname!=null){
            filterChain.doFilter(request,response);
            return;
        }

        //当用户为登录时，拦截请求跳转到登录页面
        response.sendRedirect("Login.jsp");

    }

    @Override
    public void destroy() {

    }
}
